package me.yricky.alia

import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.window.application
import me.yricky.alia.ui.AliaTheme
import me.yricky.alia.ui.WindowInst
import me.yricky.alia.ui.gdsStructPage.GDSStructPageFactory
import me.yricky.alia.ui.mainPage.MainPageFactory
import java.io.File


fun main(args:Array<String>) {
    windowApp(useArgs(args))
}

fun useArgs(args: Array<String>):List<WindowInst>{
    val li = ArrayList<WindowInst>()
    val iterator = args.iterator()

    if(args.isEmpty()){
        li.add(MainPageFactory.getWindowInst())
        App.cmdManager.active()
    } else {
        while (iterator.hasNext()){
            when(iterator.next()){
                "kts" -> {
                    if(iterator.hasNext()){
                        App.scriptEngine.eval(File(iterator.next()).reader())
                    }
                }
                "gds" -> {
                    if(iterator.hasNext()){
                        li.add(GDSStructPageFactory.getWindowInst(iterator.next()))
                    }
                }
                else -> {  }
            }
        }
    }

    return li
}

fun windowApp(windows:List<WindowInst>){
    windows.forEach { App.addWindow( it ) }
    application {
        App.setExitAction { exitApplication() }
        AliaTheme {
            val viewState by App.appState.collectAsState()
            if(viewState.activeWindows.isEmpty()){
                exitApplication()
            }
            viewState.activeWindows.lastOrNull()?.window()
        }
    }
}
